<script setup lang="ts">
import { onMounted, computed } from 'vue';
import dayjs from 'dayjs';
import { showLoading, hideLoading, showToast, redirectTo, getCurrentInstance } from '@tarojs/taro';
import { IconFont as NutIconIconFont } from '@nutui/icons-vue-taro';
import { state, imgList } from './state';
import {
  APP_PLAN_TASK_ASSET_DETAIL_QUERY,
  HANDLE_APP_TASK,
  APP_PLAN_TASK_DETAIL_QUERY,
} from '/@/api/modules/maintain/plan-task';
/**
 * 获取路由参数
 */
const params = getCurrentInstance().router?.params as {
  planTaskId: string;
  assetId: string;
  /**
   * 来源: 默认巡检 inspection/maintenance/cleaning
   */
  from?: string;
  /**
   * 来源: 扫描页面scan
   */
  module?: string;
};

const TITLE_ONE_CONSTANT = {
  maintenance: '保养情况',
  cleaning: '保洁情况',
};

const TITLE_TWO_CONSTANT = {
  maintenance: '保养异常',
  cleaning: '保洁异常',
};

const TITLE_THREE_CONSTANT = {
  maintenance: '请输入保养情况说明',
  cleaning: '请输入保洁情况说明',
};

/**
 * @function 上传文件
 * @param imgList
 */
function uploadImageChange(imgList: { key: string; src: string }[]) {
  state.taskAssetFileDto = imgList.map((i) => {
    return {
      fileType: 1,
      fileUrl: i.src,
      fileName: i.src.split('/').reverse()[0],
    };
  }) as PlanTask.TaskAssetFileDto[];
}

/**
 * 获取实际上传图片的数量
 */
function getRealUploadImageSize(): number {
  let count = 0;
  state.taskAssetItemResultDto?.forEach((item) => {
    if (item.taskAssetItemFileDto && item.taskAssetItemFileDto!.length > 0) {
      count++;
    }
  });
  return count;
}
/**
 * @description 提交信息
 */
function submit() {
  const resultValuesEmptySize =
    state.taskAssetItemResultDto?.filter((item) => !item.resultValue || item.resultValue === '')
      .length || 0;
  if (resultValuesEmptySize > 0) {
    showToast({ title: '工作流程还有项目没有填写!', icon: 'error' });
    return;
  }

  //必须上传的数量
  const requireUploadImageSize =
    state.taskAssetItemResultDto?.filter((item) => item.imageRequire === 1).length || 0;

  const realUploadImageSize = getRealUploadImageSize();

  if (requireUploadImageSize > realUploadImageSize) {
    showToast({ title: '工作流程还有图片没有上传!', icon: 'error' });
    return;
  }
  //结果状态:默认值正常
  state.planTaskAssetDto!.resultStatus = state.switchValue ? 2 : 1;
  showLoading({ title: '加载中...' });
  HANDLE_APP_TASK({
    taskAssetFileDto: state.taskAssetFileDto,
    taskAssetItemResultDto: state.taskAssetItemResultDto,
    planTaskAssetDto: state.planTaskAssetDto,
  }).then((res) => {
    hideLoading();
    showToast({
      title: res.comResp?.msg || res.comResp?.tip || '',
      icon: 'success',
    });

    redirectTo({
      url: `/pages/inspection/submit-success/index?assetId=${params.assetId}&planTaskId=${
        params.planTaskId
      }${params.from ? '&from=' + params.from : ''}${
        params.module ? '&module=' + params.module : ''
      }${state.switchValue ? '&status=2' : ''}`,
    });
  });
}

/**
 * @description 任务详情
 */
function detailQuery() {
  showLoading();
  APP_PLAN_TASK_ASSET_DETAIL_QUERY({ planTaskId: params.planTaskId, assetId: params.assetId }).then(
    (res) => {
      state.planTaskAssetDto = res.planTaskAssetDto;
      state.taskAssetFileDto = res.taskAssetFileDto || [];
      state.taskAssetItemResultDto = res.taskAssetItemResultDto || [];
      state.switchValue = state.planTaskAssetDto?.resultStatus === 2;
      state.readonly = state.planTaskAssetDto?.handleStatus === 1;
      //工作流程：类型3的模版结果赋值2
      if (!state.readonly) {
        state.taskAssetItemResultDto
          ?.filter((item) => item.itemResultType === 3)
          .forEach((item) => {
            //空字符串默认赋值‘2’
            if (!item.resultValue) {
              item.resultValue = '2';
            }
          });
      }
    },
  );
}

/**
 * 获取 TaskAssetItemResultDto项中图片imageList
 */
function getSubImageList(item: PlanTask.TaskAssetItemResultDto) {
  if (!item.taskAssetItemFileDto || !item.taskAssetItemFileDto.length) return [];

  return [...(item.taskAssetItemFileDto as PlanTask.TaskAssetItemFileDto[])].map((file) => {
    return {
      key: file.id || '',
      src: file.fileUrl || '',
    };
  });
}

/**
 * 移动端计划详情
 */
function queryPlanTaskDetail() {
  APP_PLAN_TASK_DETAIL_QUERY({ planTaskId: params.planTaskId })
    .then((res) => {
      state.planBizType = res.planTaskDto?.planBizType;
      detailQuery();
    })
    .catch();
}

onMounted(() => {
  queryPlanTaskDetail();
});

/**
 * 完成时间
 */
const finishTime = computed(() => {
  if (state.planTaskAssetDto && state.planTaskAssetDto.handleTime) {
    return dayjs(state.planTaskAssetDto.handleTime).format('YYYY-MM-DD HH:mm:ss');
  } else {
    return '--';
  }
});
</script>

<template>
  <view class="inspection-edit app-page--1">
    <app-navbar title="任务详情" />
    <scroll-view class="app-page__wrapper" :scroll-y="true" :lower-threshold="100">
      <view class="inspection-edit__wrapper">
        <nut-cell-group v-if="state.planBizType === 1">
          <nut-cell>
            <template v-slot:title>
              <text class="inspection-edit__title">资产详情</text>
            </template>
          </nut-cell>
          <nut-cell title="资产编号" :desc="state.planTaskAssetDto?.assetCode || '_'" />
          <nut-cell title="资产名称" :desc="state.planTaskAssetDto?.assetName || '_'" />
          <nut-cell title="资产分类" :desc="state.planTaskAssetDto?.assetTypeName || '_'" />
          <nut-cell title="品牌" :desc="state.planTaskAssetDto?.brandName || '_'" />
          <nut-cell title="型号" :desc="state.planTaskAssetDto?.modelName || '_'" />
          <nut-cell title="所属区域" :desc="state.planTaskAssetDto?.areaName || '_'" />
        </nut-cell-group>

        <nut-cell-group v-else>
          <nut-cell>
            <template v-slot:title>
              <text class="inspection-edit__title">区域详情</text>
            </template>
          </nut-cell>
          <nut-cell title="区域名称" :desc="state.planTaskAssetDto?.assetName || '_'" />
          <nut-cell title="所属区域" :desc="state.planTaskAssetDto?.areaName || '_'" />
        </nut-cell-group>

        <nut-cell-group>
          <nut-cell>
            <template #title>
              <text class="inspection-edit__title">工作流程</text>
            </template>
          </nut-cell>
          <nut-cell v-for="item in state.taskAssetItemResultDto" :key="item.id">
            <template #title>
              <nut-dialog
                no-cancel-btn
                title="项目内容"
                :content="item.itemContent"
                v-model:visible="item.tipVisible"
              ></nut-dialog>
              <view class="inspection-edit__content">
                <text>{{ item.itemName }}&nbsp;&nbsp;</text
                ><nut-icon-icon-font
                  name="ask"
                  @click="
                    () => {
                      item.tipVisible = true;
                    }
                  "
                />
              </view>
              <view v-if="item.imageRequire === 1">
                <app-upload-image
                  :default-image-list="getSubImageList(item)"
                  :readonly="state.readonly"
                  :module="params.from ? params.from : 'inspection'"
                  :max="1"
                  @on-change="(imgList) => {
                    item.taskAssetItemFileDto = imgList.map((i) => {
                      return {
                        fileType: 1,
                        fileUrl: i.src,
                        fileName: i.src.split('/').reverse()[0],
                      };
                    }) as PlanTask.TaskAssetItemFileDto[];
                  }"
                />
              </view>
            </template>
            <template #link v-if="item.itemResultType === 1">
              <nut-radio-group
                v-model="item.resultValue"
                direction="horizontal"
                class="inspection-edit__radio-group"
              >
                <nut-radio :disabled="state.readonly" label="1">是</nut-radio>
                <nut-radio :disabled="state.readonly" label="2">否</nut-radio>
              </nut-radio-group>
            </template>
            <template #link v-else-if="item.itemResultType === 2">
              <nut-input
                placeholder="请输入"
                class="inspection-edit__input"
                type="text"
                :readonly="state.readonly"
                v-model="item.resultValue"
                input-align="right"
              />
            </template>
            <template #link v-else-if="item.itemResultType === 3">
              <nut-button
                type="info"
                size="mini"
                :disabled="state.readonly"
                @click="
                  () => {
                    if (item.resultValue === '2') {
                      item.resultValue = '1';
                    } else {
                      item.resultValue = '2';
                    }
                  }
                "
                >{{ item.resultValue === '1' ? '已完成' : '完成' }}</nut-button
              >
            </template>
          </nut-cell>
        </nut-cell-group>
        <nut-cell-group>
          <nut-cell>
            <template v-slot:title>
              <text class="inspection-edit__title">{{
                params.from ? TITLE_ONE_CONSTANT[params.from] : '巡检情况'
              }}</text>
            </template>
          </nut-cell>
          <nut-cell :title="params.from ? TITLE_TWO_CONSTANT[params.from] : '巡检异常'">
            <template v-slot:link>
              <nut-switch v-model="state.switchValue" :disable="state.readonly" />
            </template>
          </nut-cell>
          <nut-cell>
            <template v-slot:title>
              <text>情况描述</text>
              <nut-textarea
                :placeholder="
                  params.from ? TITLE_THREE_CONSTANT[params.from] : '请输入巡检情况说明'
                "
                rows="8"
                limit-show
                text-align="left"
                :readonly="state.readonly"
                max-length="200"
                v-model="state.planTaskAssetDto!.resultDesc"
              />
            </template>
          </nut-cell>
          <nut-cell>
            <template v-slot:title>
              <text>上传图片</text>
              <view v-if="!state.readonly">
                <app-upload-image
                  @on-change="uploadImageChange"
                  :module="params.from ? params.from : 'inspection'"
                  :max="3"
                />
              </view>
              <nut-cell v-else-if="imgList && imgList.length">
                <app-upload-image :default-image-list="imgList" :readonly="state.readonly" />
              </nut-cell>
            </template>
          </nut-cell>
        </nut-cell-group>
        <view v-if="state.readonly" class="inspection-edit__finish-time">
          <view>
            <text>完成时间</text>
          </view>
          <view>
            <text>
              {{ finishTime }}
            </text>
          </view>
        </view>
      </view>
    </scroll-view>
    <view class="inspection-edit__footer" v-if="!state.readonly">
      <nut-button block type="info" @click="submit()"> 提交记录 </nut-button>
    </view>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
